<?php
/**
 * Created by PhpStorm.
 * User: king
 * Date: 2018/2/21
 * Time: 下午3:10
 */

namespace App\Traits;


use Illuminate\Http\Request;
use Intervention\Image\ImageManager;

/**
 * 文件上传trait
 *
 * Class FileUpload
 * @package App\Traits
 */
trait FileUpload
{
    protected function instance()
    {
        return ImageManager::class;
    }

    public function upload(Request $request)
    {
        $this->validateUploadFile($request);
        $uploadBuild = $this->setUploadInfo($request);
        $fileName = $this->saveFileToDir($uploadBuild);

        return $this->responseInfo($fileName);
    }

    protected function saveFileToDir($uploadBuild)
    {
        $fileName = $this->fileName();
        $path = rtrim($this->savePath()['absolute'], '/') . '/' . $fileName;
        $uploadBuild->save($path);

        return $fileName;
    }

    protected function setUploadInfo(Request $request)
    {
        $uploadInstance = $this->resolve();
        $build = $uploadInstance->make($request->file($this->uploadName())->getPathname());
        $zoom = $this->zoom();

        if ($zoom) {
            $build = $build->fit($zoom['width'], $zoom['height'], function ($c) {
                $c->aspectRatio();
            });
        }

        return $build->encode($this->suffix());
    }

    protected function zoom()
    {
        return [
//            'width'  => 100,
//            'height' => 100,
        ];
    }

    protected function suffix()
    {
        return 'png';
    }

    protected function fileName()
    {
        return uniqid(true) . '.' . $this->suffix();
    }

    protected function savePath()
    {
        return [
            'absolute' => public_path($relative = 'img/avatar'),
            'relative' => $relative,
        ];
    }

    protected function responseInfo($fileName)
    {
        $ret = [];

        foreach ($this->savePath() as $key => $item) {
            $ret[$key] = rtrim($item, '/') . '/' . $fileName;
        }

        $ret['file'] = $fileName;

        return $ret;
    }

    protected function validateUploadFile(Request $request)
    {
        // 修改时的验证：'avatar' => Rule::exists('images', 'id')->where(...)
        // 表示images表中，有这个id
        return $this->validate($request, [
            $this->uploadName() => 'required|image|max:1024',
        ]);
    }

    protected function uploadName()
    {
        return 'image';
    }

    protected function resolve()
    {
        return app()->make($this->instance());
    }
}